import yaml
import re
from model import *

def importFile(file):
  #todo: need transaction
  #try:
    data = yaml.load(file)
    for t in data:
      tag = DBLayer.getTag(t)
      if(not tag):
        tag = Tag(name=t) #todo : deal with multy tags
      tag.put()
      seq = 1
      for q in data[t]:
        question = Question(title=q)
        question.seq = seq
        seq = seq + 1
        question.put()
        tag_question = TagQuestion(tag=tag,question=question)
        tag_question.put()
        tag.qnumber = tag.qnumber + 1
        for a in data[t][q]:
          if isinstance(a,int):
            a = str(a)
          answer = Answer(text=a,question=question)
          if a.endswith('|right'):
            a = re.sub(r'\|right$','',a)
            answer.text = a
            answer.isRight = True
          # whether is right answer
          answer.put()
      tag.put()    
    return data
  #except Exception,e:
  #  print e
  
def exportFile(tagids):
  data = {}
  tags = []
  if tagids:
    tagids = tagids.split(',')
    for tagid in tagids:
        tags.push(Tag.get_by_id(tagid))
  else:
    tags = DBLayer.getAllTag()
  
  #for tag in tags:
  
  